<template>
  <div class="k-list pad">
    <div class="head">
      <span>知识列表</span>
    </div>
    <el-tabs type="border-card" class="m-t-b" @tab-click="tabClick">
      <el-tab-pane label="文章列表">
        <el-table :data="articleList" stripe border v-loading="articleLoading">
          <el-table-column label="文章标题" prop="knowledgeName"></el-table-column>
          <el-table-column label="浏览数" prop="browse"></el-table-column>
          <el-table-column label="点赞数" prop="collection"></el-table-column>
          <el-table-column label="文章封面图">
            <template slot-scope="scope">
              <img
                :src="scope.row.knowledgePic"
                style="width: 200px;"
              />
            </template>
          </el-table-column>
          <el-table-column label="发布企业全称" prop="enterpriseName"></el-table-column>
          <el-table-column label="发布企业简称" prop="forShort"></el-table-column>
          <el-table-column label="发布企业logo">
            <template slot-scope="scope">
              <img :src="scope.row.companyLogo" style="width: 80px; height: 80px;" />
            </template>
          </el-table-column>
          <el-table-column label="创建时间" prop="createDate"></el-table-column>
          <el-table-column label="操作" fixed="right" width="300">
            <template slot-scope="scope">
              <el-button type="" @click="lookArticleDetail(scope.row)">查看文章内容</el-button>
              <el-button type="primary" v-if="roleTitle === '超级管理员'" @click="setToAd(scope.row)">设为广告</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          class="flex m-t-b"
          :page-size="pageSize"
          layout="prev, pager, next"
          @current-change="handlePagi"
          :total="articleTotal"
        >
        </el-pagination>
      </el-tab-pane>
      <el-tab-pane label="视频列表">
        <el-table :data="videoList" stripe border v-loading="videoLoading">
          <el-table-column label="视频标题" prop="knowledgeName"></el-table-column>
          <el-table-column label="浏览数" prop="browse"></el-table-column>
          <el-table-column label="点赞数" prop="collection"></el-table-column>
          <el-table-column label="视频封面图">
            <template slot-scope="scope">
              <img
                :src="scope.row.knowledgePic"
                style="width: 200px;"
              />
            </template>
          </el-table-column>
          <el-table-column label="发布企业全称" prop="enterpriseName"></el-table-column>
          <el-table-column label="发布企业简称" prop="forShort"></el-table-column>
          <el-table-column label="发布企业logo">
            <template slot-scope="scope">
              <img :src="scope.row.companyLogo" style="width: 80px; height: 80px;" />
            </template>
          </el-table-column>
          <el-table-column label="创建时间" prop="createDate"></el-table-column>
          <el-table-column label="操作" fixed="right" width="300">
            <template slot-scope="scope">
              <el-button type="priamry" @click="lookVideo(scope.row)">查看视频</el-button>
              <el-button type="primary" v-if="roleTitle === '超级管理员'" @click="setToAd(scope.row)">设为广告</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          class="flex m-t-b"
          :page-size="pageSize"
          layout="prev, pager, next"
          @current-change="handlePagi"
          :total="videoTotal"
        >
        </el-pagination>
      </el-tab-pane>
      <el-tab-pane label="知识广告" v-if="roleTitle === '超级管理员'">
        <el-table :data="adList" stripe border>
          <el-table-column label="广告标题" prop="title"></el-table-column>
          <el-table-column label="广告图片">
            <template slot-scope="scope">
              <img :src="scope.row.advertisementPic" style="width: 200px;" />
            </template>
          </el-table-column>
          <el-table-column label="类型">
            <template slot-scope="scope">
              {{scope.row.knowledgeType == '0' ? '文章' : '视频'}}
            </template>
          </el-table-column>
          <el-table-column label="浏览量" prop="browse"></el-table-column>
          <el-table-column label="点赞数" prop="collection"></el-table-column>
          <el-table-column label="创建时间" prop="createDate"></el-table-column>
          <el-table-column label="是否启用">
            <template slot-scope="scope">
              <el-switch
                active-text="启用"
                inactive-text="禁用"
                v-model="scope.row.enable"
                @change="changeStatus($event, scope.row)"
              ></el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button type="primary" @click="lookDetail(scope.row)">查看{{scope.row.knowledgeType == '0' ? '文章' : '视频'}}</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
      <el-tab-pane label="测试">
        <el-upload
          action="http://localhost:8080/result/symptom/relation/batch"
          :http-request="handleUpload"
          :show-file-list="false"
        >
          <el-button :loading="isDoing" type="primary">批量上传</el-button>
        </el-upload>
      </el-tab-pane>
    </el-tabs>
    <el-dialog title="文章详情" :visible.sync="showArticle">
      <div
        style="text-align: center; font-size: 20px; font-weight: bold; margin-bottom: 10px;"
      >{{currentArticle.knowledgeName}}</div>
      <el-input style="line-height: 20px;" type="textarea" rows="30" disabled v-model="currentArticle.knowledgeDesc" />
    </el-dialog>
    <el-dialog title="视频详情" :visible.sync="showVideo">
      <div
        style="text-align: center; font-size: 20px; font-weight: bold; margin-bottom: 10px;"
      >{{currentVideo.knowledgeName}}</div>
      <video
        style="width: 100%;"
        :src="currentVideo.knowledgeVideo"
        controls
        autoplay
      ></video>
    </el-dialog>

    <el-dialog title="设置广告" :visible.sync="showAdSetting">
      <el-form label-position="top" :model="ad">
        <el-form-item label="广告类型">
          <el-radio-group v-model="adType">
            <el-radio
              v-for="(item, i) in adTypes"
              :key="i"
              :label="i + 1"
            >{{item}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="广告标题">
          <el-input v-model="ad.title" />
        </el-form-item>
        <el-form-item label="广告图片">
          <el-upload
            class="avatar-uploader"
            action="https://jsonplaceholder.typicode.com/posts/"
            :show-file-list="true"
            :http-request="uploadAdImg"
          >
            <img v-if="ad.advertisementPic" :src="ad.advertisementPic" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showAdSetting = false">取 消</el-button>
        <el-button type="primary" @click="fetchAddAd" :loading="isAdding">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  getKnowledgeList,
  createAd,
  getAdList,
  changeAdStatus
} from '../api/version2';
import XLSX from 'xlsx';
import { formatDate, fileToBase64, excel2Json } from '../util';
import { uploadImage } from '../api';
export default {
  name: 'KnowledgeList',
  data () {
    return {
      knowledgeList: [],
      adType: 1,
      videoTotal: 0,
      articleTotal: 0,
      isAdding: false,
      adList: [],
      loading: false,
      articleLoading: false,
      videoLoading: false,
      roleTitle: '',
      pageSize: 10,
      type: 0,
      articleList: [],
      videoList: [],
      currentArticle: {},
      showArticle: false,
      showAdSetting: false,
      showVideo: false,
      currentVideo: {},
      enterpriseId: null,
      adTypes: ['首页弹窗广告'],
      isDoing: false,
      ad: {
        knowledgeId: '',
        advertisementPic: '',
        title: ''
      },
      selectOne: ''
    }
  },
  methods: {
    fetchKnowledgeList (index) { // 查询知识列表
      this[this.type === 0 ? 'articleLoading' : (this.type === 1 ? 'videoLoading' : '')] = true;
      getKnowledgeList({
        index,
        count: this.pageSize,
        queryParam: {
          knowledgeType: this.type,
          enterpriseId: this.enterpriseId
        }
      })
      .then(res => {
        this[this.type === 0 ? 'articleLoading' : (this.type === 1 ? 'videoLoading' : '')] = false;
        let list = res.data.data.list || [];
        list.forEach(item => {
          item.createDate = formatDate(item.createDate, 'ZH')
        });
        this[this.type === 0 ? 'articleList' : (this.type === 1 ? 'videoList' : '')] = list;
        this[this.type === 0 ? 'articleTotal' : (this.type === 1 ? 'videoTotal' : '')] = res.data.data.totalRecord
      })
      .catch(e => {
        this[this.type === 0 ? 'articleLoading' : (this.type === 1 ? 'videoLoading' : '')] = false;
      })
    },
    uploadAdImg ({ file }) { // 上传广告图片
      const that = this;
      fileToBase64(file, str => {
        uploadImage(str)
        .then(res => {
          let path = res.data.data.path;
          path = path.replace('http:', 'https:');
          that.ad.advertisementPic = path
        })
        .catch(e => {

        })
      })
    },
    fetchAddAd () { // 设置为广告
      this.isAdding = true;
      createAd(this.ad)
      .then(res => {
        this.$message.success('添加成功!')
        this.isAdding = false;
        this.showAdSetting = false;
        this.fetchAdList()
      })
      .catch(e => {
        this.isAdding = false
      })
    },
    handleUpload ({ file }) {
      this.isDoing = true;
      const that = this
      excel2Json(file, this.$xlsx, (worker, data) => {
        console.log(worker)
        let list = [];
        for (let key in worker.Sheets) {
          if (worker.Sheets[key]) {
            let temp = XLSX.utils.sheet_to_json(worker.Sheets[key])
          list.push(...temp);
          }
        };
        let badList = [];
        that.isDoing = false
        console.log(list);
        let reg = /^111-111-111$/;
        for (let i = 0; i < list.length; i ++) {
          if (!list[i].sno) {
            // badList.push(list[i].id)
          } else {
            if (reg.test(list[i].sno)) {
              console.log(list[i].sno);

              badList.push(list[i].id)
            }
          }
        };
        console.log('异常名单');
        console.log(badList)
      })
    },
    setToAd (item) {
      this.ad.knowledgeId = item.knowledgeId;
      this.showAdSetting = true
    },
    handlePagi (page) { // 分页事件
      this.fetchKnowledgeList(page)
    },
    tabClick ({ index }) { // tab页点击
      if (index > 2) return;
      this.type = Number(index);
      if (index == 0 & !this.articleList.length) {
        this.fetchKnowledgeList(1)
      } else if (index == 1 && !this.videoList.length) {
        this.fetchKnowledgeList(1)
      }
    },
    lookArticleDetail (article) { // 查看文章详情
      this.currentArticle = article;
      this.showArticle = true
    },
    lookVideo (video) { // 查看视频
      this.currentVideo = video;
      this.showVideo = true
    },
    fetchAdList () { // 查询广告列表
      getAdList()
      .then(res => {
        let list = res.data.data || [];
        list.forEach(item => {
          item.createDate = formatDate(item.createDate, 'ZH');
          item.enable = Boolean(item.advertisementStatus)
        });
        this.adList = list
      })
      .catch(e => {

      })
    },
    lookDetail (row) { // 查看知识详情
      if (row.knowledgeType == '0') { // 文章
        this.currentArticle = row;
        this.showArticle = true
      } else if (row.knowledgeType == '1') { // 视频
        this.currentVideo = row;
        this.showVideo = true
      }
    },
    changeStatus (e, row) { // 切换状态
      this.$confirm(`确定 ${e ? '启用' : '禁用'} 该广告吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(r => {
        changeAdStatus({
          advertisementId: row.advertisementId,
          advertisementStatus: Number(e)
        })
        .then(res => {
          this.$message.success('操作成功');
          this.fetchAdList()
        })
        .catch(e => {})
      })
      .catch(err => {
        row.enable = !e
      })
    }
  },
  created () {
    let roleTitle = sessionStorage.getItem('roleTitle') || '';
    this.roleTitle = roleTitle;
    let enterpriseId = sessionStorage.getItem('enterpriseId');
    if (roleTitle == '公司') {
      this.enterpriseId = enterpriseId
    };
    this.fetchKnowledgeList(1);
    this.fetchAdList()
  }
}
</script>
<style lang="scss">

</style>
